<?php
/**
 * Created by PhpStorm.
 * User: Charles
 * Date: 2017/11/5
 * Time: 11:42
 */

namespace App\Models;


class WechatRedPacket
{
    private $amount = 0;
    private $openid = '';
    private $attributes = [];
    /**
     * WechatRedPacket constructor.
     * @param $openid openid
     * @param $amount 金额 分
     */
    public function __construct($openid, $amount)
    {
        if ($amount < 100) {
            throw new \Exception('金额不能少于1块');
        }
        $this->openid = $openid;
        $this->amount = $amount;

    }

    public function prepareAttributes()
    {
        $this->attributes = [
            'mch_billno'       => 'REDPACKET' . date('YmdHis') . substr(uniqid(), 0, 5),
            'send_name'        => '红包',
            're_openid'        => $this->openid,
            'total_num'        => 1,                     //普通红包固定为1，裂变红包不小于3
            'total_amount'     => $this->amount,         //单位为分，普通红包不小于100，裂变红包不小于300
            'wishing'          => '祝您财源广进',
            'client_ip'        => $this->getClientIp(),  //可不传，不传则由 SDK 取当前客户端 IP
            'act_name'         => '万事如意',
            'remark'           => '恭喜发财',
        ];
    }

    private function getClientIp()
    {
        $ip = \EasyWeChat\Payment\get_client_ip();
        if ($ip == '127.0.0.1' || $ip = '::1') {
            $ip = '120.204.77.4';
        }
        return $ip;
    }

    public function send()
    {
        $this->prepareAttributes();
        return EasyWechat::getApp()->lucky_money->sendNormal($this->attributes);
    }
}